#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
全方位功能测试套件 v1.0
针对privilege-maDev项目的全面功能验证

功能特性:
- 🔍 核心功能模块测试
- 🚀 自动化部署测试
- 🛡️ 安全规避功能测试
- 🧠 智能决策系统测试
- 📊 红队工具测试
- 📈 集成测试和端到端验证
- 📋 详细测试报告生成
"""

import os
import sys
import json
import time
import subprocess
import threading
import traceback
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Any, Optional

# 添加项目路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

class TestResult:
    """测试结果类"""
    def __init__(self, test_name: str):
        self.test_name = test_name
        self.success = False
        self.error_message = ""
        self.execution_time = 0.0
        self.details = {}
        self.start_time = None
        self.end_time = None
    
    def start(self):
        self.start_time = time.time()
    
    def finish(self, success: bool, error_message: str = "", details: Dict = None):
        self.end_time = time.time()
        self.execution_time = self.end_time - self.start_time if self.start_time else 0.0
        self.success = success
        self.error_message = error_message
        self.details = details or {}

class ComprehensiveTestSuite:
    """全面测试套件"""
    
    def __init__(self):
        self.test_results = []
        self.session_id = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.test_report = {
            'session_id': self.session_id,
            'start_time': datetime.now().isoformat(),
            'test_results': [],
            'summary': {},
            'environment': {}
        }
        
        # 测试配置
        self.test_config = {
            'target_ip': '192.168.10.129',
            'target_port': 8888,
            'test_timeout': 30,
            'cleanup_after_test': True
        }
        
        print(f"🚀 全方位功能测试套件启动 - 会话ID: {self.session_id}")
        print("="*70)
    
    def run_all_tests(self):
        """运行所有测试"""
        try:
            # 收集环境信息
            self._collect_environment_info()
            
            # 1. 核心功能模块测试
            self._test_core_modules()
            
            # 2. 自动化部署测试
            self._test_automation_modules()
            
            # 3. 红队工具测试
            self._test_redteam_modules()
            
            # 4. 安全规避测试
            self._test_security_evasion()
            
            # 5. 智能决策系统测试
            self._test_intelligence_modules()
            
            # 6. 集成测试
            self._test_integration_scenarios()
            
            # 生成测试报告
            self._generate_test_report()
            
        except Exception as e:
            print(f"❌ 测试套件执行失败: {e}")
            traceback.print_exc()
    
    def _collect_environment_info(self):
        """收集环境信息"""
        print("📋 收集测试环境信息...")
        
        try:
            # 系统信息
            import platform
            self.test_report['environment'] = {
                'platform': platform.platform(),
                'python_version': platform.python_version(),
                'architecture': platform.architecture(),
                'processor': platform.processor(),
                'hostname': platform.node(),
                'project_root': str(project_root),
                'test_time': datetime.now().isoformat()
            }
            
            # 检查项目结构
            key_directories = ['modules', 'apps', 'config', 'scripts', 'docs']
            missing_dirs = []
            for dir_name in key_directories:
                if not (project_root / dir_name).exists():
                    missing_dirs.append(dir_name)
            
            self.test_report['environment']['missing_directories'] = missing_dirs
            self.test_report['environment']['project_structure_complete'] = len(missing_dirs) == 0
            
            print(f"✅ 环境信息收集完成")
            
        except Exception as e:
            print(f"⚠️ 环境信息收集失败: {e}")
    
    def _test_core_modules(self):
        """测试核心功能模块"""
        print("\n🔍 测试核心功能模块...")
        
        # 测试系统检测功能
        self._test_system_detection()
        
        # 测试漏洞利用模块
        self._test_exploit_modules()
        
        # 测试持久化模块
        self._test_persistence_modules()
        
        # 测试环境检测模块
        self._test_environment_modules()
    
    def _test_system_detection(self):
        """测试系统检测功能"""
        test_result = TestResult("系统检测功能")
        test_result.start()
        
        try:
            print("  📊 测试系统检测功能...")
            
            # 测试check.py
            check_script = project_root / "apps" / "check.py"
            if check_script.exists():
                # 运行系统检测（非交互模式）
                result = subprocess.run([
                    sys.executable, str(check_script)
                ], capture_output=True, text=True, timeout=30, 
                input="\n" * 10)  # 提供默认输入
                
                success = result.returncode == 0 or "检测完成" in result.stdout
                details = {
                    'returncode': result.returncode,
                    'stdout_length': len(result.stdout),
                    'stderr_length': len(result.stderr),
                    'has_output': len(result.stdout) > 0
                }
                
                test_result.finish(success, result.stderr if not success else "", details)
                print(f"    ✅ 系统检测功能测试完成")
            else:
                test_result.finish(False, "check.py文件不存在")
                print(f"    ❌ check.py文件不存在")
                
        except subprocess.TimeoutExpired:
            test_result.finish(False, "测试超时")
            print(f"    ⚠️ 系统检测测试超时")
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 系统检测测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_exploit_modules(self):
        """测试漏洞利用模块"""
        test_result = TestResult("漏洞利用模块")
        test_result.start()
        
        try:
            print("  🎯 测试漏洞利用模块...")
            
            # 测试主要利用脚本
            exploit_script = project_root / "modules" / "exploits" / "main_exploit.py"
            if exploit_script.exists():
                # 导入测试
                sys.path.insert(0, str(project_root / "modules" / "exploits"))
                try:
                    import main_exploit
                    # 检查关键函数是否存在
                    has_main = hasattr(main_exploit, 'main')
                    has_banner = hasattr(main_exploit, 'print_banner')
                    
                    details = {
                        'module_imported': True,
                        'has_main_function': has_main,
                        'has_banner_function': has_banner
                    }
                    
                    success = has_main and has_banner
                    test_result.finish(success, "", details)
                    print(f"    ✅ 漏洞利用模块导入成功")
                    
                except ImportError as e:
                    test_result.finish(False, f"模块导入失败: {e}")
                    print(f"    ❌ 漏洞利用模块导入失败: {e}")
            else:
                test_result.finish(False, "main_exploit.py文件不存在")
                print(f"    ❌ main_exploit.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 漏洞利用模块测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_persistence_modules(self):
        """测试持久化模块"""
        test_result = TestResult("持久化模块")
        test_result.start()
        
        try:
            print("  🔒 测试持久化模块...")
            
            persistence_dir = project_root / "modules" / "persistence"
            if persistence_dir.exists():
                # 检查关键持久化文件
                key_files = [
                    "backdoor_checks.py",
                    "ssh_checks.py", 
                    "persistence_manager.py"
                ]
                
                existing_files = []
                for file_name in key_files:
                    file_path = persistence_dir / file_name
                    if file_path.exists():
                        existing_files.append(file_name)
                
                details = {
                    'total_key_files': len(key_files),
                    'existing_files': existing_files,
                    'missing_files': [f for f in key_files if f not in existing_files],
                    'completion_rate': len(existing_files) / len(key_files)
                }
                
                success = len(existing_files) >= len(key_files) * 0.7  # 70%的文件存在即认为成功
                test_result.finish(success, "", details)
                print(f"    ✅ 持久化模块检查完成 ({len(existing_files)}/{len(key_files)})")
                
            else:
                test_result.finish(False, "persistence目录不存在")
                print(f"    ❌ persistence目录不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 持久化模块测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_environment_modules(self):
        """测试环境检测模块"""
        test_result = TestResult("环境检测模块")
        test_result.start()
        
        try:
            print("  🌍 测试环境检测模块...")
            
            env_dir = project_root / "modules" / "environment"
            if env_dir.exists():
                # 检查环境检测文件
                env_files = [
                    "detector.py",
                    "capabilities.py",
                    "cloud_detector.py",
                    "container_detector.py"
                ]
                
                existing_files = []
                for file_name in env_files:
                    file_path = env_dir / file_name
                    if file_path.exists():
                        existing_files.append(file_name)
                
                details = {
                    'total_files': len(env_files),
                    'existing_files': existing_files,
                    'completion_rate': len(existing_files) / len(env_files)
                }
                
                success = len(existing_files) >= 2  # 至少2个文件存在
                test_result.finish(success, "", details)
                print(f"    ✅ 环境检测模块检查完成 ({len(existing_files)}/{len(env_files)})")
                
            else:
                test_result.finish(False, "environment目录不存在")
                print(f"    ❌ environment目录不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 环境检测模块测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_automation_modules(self):
        """测试自动化部署模块"""
        print("\n🚀 测试自动化部署模块...")
        
        # 测试一键部署
        self._test_one_click_deployment()
        
        # 测试批量部署
        self._test_batch_deployment()
        
        # 测试部署验证
        self._test_deployment_verification()
    
    def _test_one_click_deployment(self):
        """测试一键部署功能"""
        test_result = TestResult("一键部署功能")
        test_result.start()
        
        try:
            print("  🎯 测试一键部署功能...")
            
            deployment_script = project_root / "modules" / "automation" / "one_click_deployment.py"
            if deployment_script.exists():
                # 尝试导入模块
                sys.path.insert(0, str(project_root / "modules" / "automation"))
                try:
                    import one_click_deployment
                    
                    # 检查关键类和方法
                    has_class = hasattr(one_click_deployment, 'OneClickDeployment')
                    
                    details = {
                        'module_imported': True,
                        'has_main_class': has_class
                    }
                    
                    if has_class:
                        # 尝试实例化（不执行实际部署）
                        try:
                            deployment = one_click_deployment.OneClickDeployment()
                            details['class_instantiated'] = True
                        except Exception as e:
                            details['class_instantiated'] = False
                            details['instantiation_error'] = str(e)
                    
                    success = has_class
                    test_result.finish(success, "", details)
                    print(f"    ✅ 一键部署模块检查完成")
                    
                except ImportError as e:
                    test_result.finish(False, f"模块导入失败: {e}")
                    print(f"    ❌ 一键部署模块导入失败: {e}")
            else:
                test_result.finish(False, "one_click_deployment.py文件不存在")
                print(f"    ❌ one_click_deployment.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 一键部署测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_batch_deployment(self):
        """测试批量部署功能"""
        test_result = TestResult("批量部署功能")
        test_result.start()
        
        try:
            print("  📦 测试批量部署功能...")
            
            batch_script = project_root / "modules" / "automation" / "batch_deployment_engine.py"
            if batch_script.exists():
                # 检查文件大小和内容
                file_size = batch_script.stat().st_size
                
                details = {
                    'file_exists': True,
                    'file_size': file_size,
                    'file_size_reasonable': file_size > 1000  # 至少1KB
                }
                
                success = file_size > 1000
                test_result.finish(success, "", details)
                print(f"    ✅ 批量部署模块检查完成")
                
            else:
                test_result.finish(False, "batch_deployment_engine.py文件不存在")
                print(f"    ❌ batch_deployment_engine.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 批量部署测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_deployment_verification(self):
        """测试部署验证功能"""
        test_result = TestResult("部署验证功能")
        test_result.start()
        
        try:
            print("  ✅ 测试部署验证功能...")
            
            verification_script = project_root / "modules" / "automation" / "deployment_verification.py"
            if verification_script.exists():
                file_size = verification_script.stat().st_size
                
                details = {
                    'file_exists': True,
                    'file_size': file_size
                }
                
                success = file_size > 500
                test_result.finish(success, "", details)
                print(f"    ✅ 部署验证模块检查完成")
                
            else:
                test_result.finish(False, "deployment_verification.py文件不存在")
                print(f"    ❌ deployment_verification.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 部署验证测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_redteam_modules(self):
        """测试红队工具模块"""
        print("\n🔴 测试红队工具模块...")
        
        # 测试红队控制器
        self._test_redteam_controller()
        
        # 测试红队启动器
        self._test_redteam_launcher()
        
        # 测试C2通信
        self._test_c2_communication()
    
    def _test_redteam_controller(self):
        """测试红队控制器"""
        test_result = TestResult("红队控制器")
        test_result.start()
        
        try:
            print("  🎮 测试红队控制器...")
            
            controller_script = project_root / "modules" / "redteam" / "redteam_controller.py"
            if controller_script.exists():
                file_size = controller_script.stat().st_size
                
                details = {
                    'file_exists': True,
                    'file_size': file_size,
                    'file_size_reasonable': file_size > 2000
                }
                
                success = file_size > 2000
                test_result.finish(success, "", details)
                print(f"    ✅ 红队控制器检查完成")
                
            else:
                test_result.finish(False, "redteam_controller.py文件不存在")
                print(f"    ❌ redteam_controller.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 红队控制器测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_redteam_launcher(self):
        """测试红队启动器"""
        test_result = TestResult("红队启动器")
        test_result.start()
        
        try:
            print("  🚀 测试红队启动器...")
            
            launcher_script = project_root / "apps" / "redteam_launcher.py"
            if launcher_script.exists():
                # 尝试运行帮助命令
                result = subprocess.run([
                    sys.executable, str(launcher_script), "--help"
                ], capture_output=True, text=True, timeout=10)
                
                details = {
                    'file_exists': True,
                    'help_command_works': result.returncode == 0,
                    'has_help_output': "help" in result.stdout.lower() or "usage" in result.stdout.lower()
                }
                
                success = result.returncode == 0 or details['has_help_output']
                test_result.finish(success, result.stderr if not success else "", details)
                print(f"    ✅ 红队启动器测试完成")
                
            else:
                test_result.finish(False, "redteam_launcher.py文件不存在")
                print(f"    ❌ redteam_launcher.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 红队启动器测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_c2_communication(self):
        """测试C2通信功能"""
        test_result = TestResult("C2通信功能")
        test_result.start()
        
        try:
            print("  📡 测试C2通信功能...")
            
            c2_script = project_root / "modules" / "redteam" / "c2_interface.py"
            if c2_script.exists():
                file_size = c2_script.stat().st_size
                
                details = {
                    'file_exists': True,
                    'file_size': file_size
                }
                
                success = file_size > 1000
                test_result.finish(success, "", details)
                print(f"    ✅ C2通信模块检查完成")
                
            else:
                test_result.finish(False, "c2_interface.py文件不存在")
                print(f"    ❌ c2_interface.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ C2通信测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_security_evasion(self):
        """测试安全规避功能"""
        print("\n🛡️ 测试安全规避功能...")
        
        # 测试EDR规避
        self._test_edr_evasion()
        
        # 测试隐蔽性功能
        self._test_stealth_features()
        
        # 测试反分析技术
        self._test_anti_analysis()
    
    def _test_edr_evasion(self):
        """测试EDR规避功能"""
        test_result = TestResult("EDR规避功能")
        test_result.start()
        
        try:
            print("  🔍 测试EDR规避功能...")
            
            edr_dir = project_root / "modules" / "evasion"
            if edr_dir.exists():
                edr_files = [
                    "edr_detection.py",
                    "edr_strategies.py",
                    "dynamic_behavior_evasion.py"
                ]
                
                existing_files = []
                for file_name in edr_files:
                    file_path = edr_dir / file_name
                    if file_path.exists():
                        existing_files.append(file_name)
                
                details = {
                    'total_files': len(edr_files),
                    'existing_files': existing_files,
                    'completion_rate': len(existing_files) / len(edr_files)
                }
                
                success = len(existing_files) >= 2
                test_result.finish(success, "", details)
                print(f"    ✅ EDR规避模块检查完成 ({len(existing_files)}/{len(edr_files)})")
                
            else:
                test_result.finish(False, "evasion目录不存在")
                print(f"    ❌ evasion目录不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ EDR规避测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_stealth_features(self):
        """测试隐蔽性功能"""
        test_result = TestResult("隐蔽性功能")
        test_result.start()
        
        try:
            print("  👻 测试隐蔽性功能...")
            
            stealth_dir = project_root / "modules" / "stealth"
            if stealth_dir.exists():
                stealth_files = list(stealth_dir.glob("*.py"))
                
                details = {
                    'stealth_files_count': len(stealth_files),
                    'stealth_files': [f.name for f in stealth_files]
                }
                
                success = len(stealth_files) >= 2
                test_result.finish(success, "", details)
                print(f"    ✅ 隐蔽性模块检查完成 ({len(stealth_files)}个文件)")
                
            else:
                test_result.finish(False, "stealth目录不存在")
                print(f"    ❌ stealth目录不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 隐蔽性功能测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_anti_analysis(self):
        """测试反分析技术"""
        test_result = TestResult("反分析技术")
        test_result.start()
        
        try:
            print("  🔬 测试反分析技术...")
            
            security_dir = project_root / "modules" / "security"
            if security_dir.exists():
                anti_analysis_files = [
                    "anti_analysis_techniques.py",
                    "anti_static_detection.py"
                ]
                
                existing_files = []
                for file_name in anti_analysis_files:
                    file_path = security_dir / file_name
                    if file_path.exists():
                        existing_files.append(file_name)
                
                details = {
                    'total_files': len(anti_analysis_files),
                    'existing_files': existing_files
                }
                
                success = len(existing_files) >= 1
                test_result.finish(success, "", details)
                print(f"    ✅ 反分析技术检查完成 ({len(existing_files)}/{len(anti_analysis_files)})")
                
            else:
                test_result.finish(False, "security目录不存在")
                print(f"    ❌ security目录不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 反分析技术测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_intelligence_modules(self):
        """测试智能决策模块"""
        print("\n🧠 测试智能决策模块...")
        
        # 测试智能决策引擎
        self._test_decision_engine()
        
        # 测试风险评估
        self._test_risk_assessment()
        
        # 测试场景模板引擎
        self._test_scenario_engine()
    
    def _test_decision_engine(self):
        """测试智能决策引擎"""
        test_result = TestResult("智能决策引擎")
        test_result.start()
        
        try:
            print("  🎯 测试智能决策引擎...")
            
            decision_script = project_root / "modules" / "intelligence" / "intelligent_decision_engine.py"
            if decision_script.exists():
                # 尝试导入模块
                sys.path.insert(0, str(project_root / "modules" / "intelligence"))
                try:
                    import intelligent_decision_engine
                    
                    # 检查关键类
                    has_engine = hasattr(intelligent_decision_engine, 'IntelligentDecisionEngine')
                    has_env_class = hasattr(intelligent_decision_engine, 'SystemEnvironment')
                    
                    details = {
                        'module_imported': True,
                        'has_decision_engine': has_engine,
                        'has_environment_class': has_env_class
                    }
                    
                    success = has_engine and has_env_class
                    test_result.finish(success, "", details)
                    print(f"    ✅ 智能决策引擎检查完成")
                    
                except ImportError as e:
                    test_result.finish(False, f"模块导入失败: {e}")
                    print(f"    ❌ 智能决策引擎导入失败: {e}")
            else:
                test_result.finish(False, "intelligent_decision_engine.py文件不存在")
                print(f"    ❌ intelligent_decision_engine.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 智能决策引擎测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_risk_assessment(self):
        """测试风险评估功能"""
        test_result = TestResult("风险评估功能")
        test_result.start()
        
        try:
            print("  ⚖️ 测试风险评估功能...")
            
            risk_script = project_root / "modules" / "intelligence" / "risk_assessment_engine.py"
            if risk_script.exists():
                file_size = risk_script.stat().st_size
                
                details = {
                    'file_exists': True,
                    'file_size': file_size
                }
                
                success = file_size > 1000
                test_result.finish(success, "", details)
                print(f"    ✅ 风险评估模块检查完成")
                
            else:
                test_result.finish(False, "risk_assessment_engine.py文件不存在")
                print(f"    ❌ risk_assessment_engine.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 风险评估测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_scenario_engine(self):
        """测试场景模板引擎"""
        test_result = TestResult("场景模板引擎")
        test_result.start()
        
        try:
            print("  📋 测试场景模板引擎...")
            
            scenario_script = project_root / "modules" / "intelligence" / "scenario_template_engine.py"
            if scenario_script.exists():
                file_size = scenario_script.stat().st_size
                
                details = {
                    'file_exists': True,
                    'file_size': file_size
                }
                
                success = file_size > 1000
                test_result.finish(success, "", details)
                print(f"    ✅ 场景模板引擎检查完成")
                
            else:
                test_result.finish(False, "scenario_template_engine.py文件不存在")
                print(f"    ❌ scenario_template_engine.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 场景模板引擎测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_integration_scenarios(self):
        """测试集成场景"""
        print("\n🔗 测试集成场景...")
        
        # 测试终极持久化测试器
        self._test_ultimate_persistence_tester()
        
        # 测试端到端场景
        self._test_end_to_end_scenarios()
    
    def _test_ultimate_persistence_tester(self):
        """测试终极持久化测试器"""
        test_result = TestResult("终极持久化测试器")
        test_result.start()
        
        try:
            print("  🎯 测试终极持久化测试器...")
            
            tester_script = project_root / "scripts" / "ultimate_persistence_tester.py"
            if tester_script.exists():
                # 运行帮助命令
                result = subprocess.run([
                    sys.executable, str(tester_script), "--help"
                ], capture_output=True, text=True, timeout=15)
                
                details = {
                    'file_exists': True,
                    'help_command_works': result.returncode == 0,
                    'has_help_output': "help" in result.stdout.lower() or "usage" in result.stdout.lower(),
                    'stdout_length': len(result.stdout)
                }
                
                success = result.returncode == 0 or details['has_help_output']
                test_result.finish(success, result.stderr if not success else "", details)
                print(f"    ✅ 终极持久化测试器检查完成")
                
            else:
                test_result.finish(False, "ultimate_persistence_tester.py文件不存在")
                print(f"    ❌ ultimate_persistence_tester.py文件不存在")
                
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 终极持久化测试器测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _test_end_to_end_scenarios(self):
        """测试端到端场景"""
        test_result = TestResult("端到端场景测试")
        test_result.start()
        
        try:
            print("  🔄 测试端到端场景...")
            
            # 检查是否有演示脚本
            demo_scripts = list((project_root / "examples").glob("demo*.py"))
            
            details = {
                'demo_scripts_count': len(demo_scripts),
                'demo_scripts': [script.name for script in demo_scripts]
            }
            
            success = len(demo_scripts) >= 2
            test_result.finish(success, "", details)
            print(f"    ✅ 端到端场景检查完成 ({len(demo_scripts)}个演示脚本)")
            
        except Exception as e:
            test_result.finish(False, str(e))
            print(f"    ❌ 端到端场景测试失败: {e}")
        
        self.test_results.append(test_result)
    
    def _generate_test_report(self):
        """生成测试报告"""
        print("\n📊 生成测试报告...")
        
        # 统计测试结果
        total_tests = len(self.test_results)
        passed_tests = sum(1 for result in self.test_results if result.success)
        failed_tests = total_tests - passed_tests
        success_rate = (passed_tests / total_tests * 100) if total_tests > 0 else 0
        
        # 更新测试报告
        self.test_report['end_time'] = datetime.now().isoformat()
        self.test_report['summary'] = {
            'total_tests': total_tests,
            'passed_tests': passed_tests,
            'failed_tests': failed_tests,
            'success_rate': round(success_rate, 2),
            'total_execution_time': sum(result.execution_time for result in self.test_results)
        }
        
        # 添加详细测试结果
        for result in self.test_results:
            self.test_report['test_results'].append({
                'test_name': result.test_name,
                'success': result.success,
                'execution_time': round(result.execution_time, 3),
                'error_message': result.error_message,
                'details': result.details
            })
        
        # 保存测试报告
        report_file = project_root / "reports" / f"comprehensive_test_report_{self.session_id}.json"
        report_file.parent.mkdir(exist_ok=True)
        
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(self.test_report, f, indent=2, ensure_ascii=False)
        
        # 生成Markdown报告
        self._generate_markdown_report(report_file.with_suffix('.md'))
        
        # 显示测试结果摘要
        print("\n" + "="*70)
        print("📋 测试结果摘要")
        print("="*70)
        print(f"总测试数: {total_tests}")
        print(f"通过测试: {passed_tests}")
        print(f"失败测试: {failed_tests}")
        print(f"成功率: {success_rate:.1f}%")
        print(f"总执行时间: {self.test_report['summary']['total_execution_time']:.2f}秒")
        print(f"测试报告: {report_file}")
        
        # 显示失败的测试
        if failed_tests > 0:
            print(f"\n❌ 失败的测试:")
            for result in self.test_results:
                if not result.success:
                    print(f"  - {result.test_name}: {result.error_message}")
        
        print("="*70)
    
    def _generate_markdown_report(self, report_file):
        """生成Markdown格式的测试报告"""
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                f.write(f"# 全方位功能测试报告\n\n")
                f.write(f"**测试会话ID**: {self.session_id}\n")
                f.write(f"**测试时间**: {self.test_report['start_time']} - {self.test_report['end_time']}\n\n")
                
                # 测试摘要
                summary = self.test_report['summary']
                f.write(f"## 测试摘要\n\n")
                f.write(f"- **总测试数**: {summary['total_tests']}\n")
                f.write(f"- **通过测试**: {summary['passed_tests']}\n")
                f.write(f"- **失败测试**: {summary['failed_tests']}\n")
                f.write(f"- **成功率**: {summary['success_rate']}%\n")
                f.write(f"- **总执行时间**: {summary['total_execution_time']:.2f}秒\n\n")
                
                # 环境信息
                env = self.test_report['environment']
                f.write(f"## 测试环境\n\n")
                f.write(f"- **平台**: {env.get('platform', 'Unknown')}\n")
                f.write(f"- **Python版本**: {env.get('python_version', 'Unknown')}\n")
                f.write(f"- **架构**: {env.get('architecture', 'Unknown')}\n")
                f.write(f"- **主机名**: {env.get('hostname', 'Unknown')}\n")
                f.write(f"- **项目结构完整**: {'✅' if env.get('project_structure_complete') else '❌'}\n\n")
                
                # 详细测试结果
                f.write(f"## 详细测试结果\n\n")
                for result in self.test_report['test_results']:
                    status = "✅ 通过" if result['success'] else "❌ 失败"
                    f.write(f"### {result['test_name']} - {status}\n\n")
                    f.write(f"- **执行时间**: {result['execution_time']}秒\n")
                    
                    if not result['success'] and result['error_message']:
                        f.write(f"- **错误信息**: {result['error_message']}\n")
                    
                    if result['details']:
                        f.write(f"- **详细信息**:\n")
                        for key, value in result['details'].items():
                            f.write(f"  - {key}: {value}\n")
                    
                    f.write(f"\n")
                
                print(f"✅ Markdown报告已生成: {report_file}")
                
        except Exception as e:
            print(f"⚠️ Markdown报告生成失败: {e}")

def main():
    """主函数"""
    print("🚀 启动全方位功能测试套件...")
    
    try:
        # 创建测试套件实例
        test_suite = ComprehensiveTestSuite()
        
        # 运行所有测试
        test_suite.run_all_tests()
        
        print("\n🎉 全方位功能测试完成!")
        
    except KeyboardInterrupt:
        print("\n⚠️ 测试被用户中断")
    except Exception as e:
        print(f"\n❌ 测试套件执行失败: {e}")
        traceback.print_exc()

if __name__ == "__main__":
    main()